import React from 'react';
import * as THREE from 'three';
import Scene from '../Scene';
let group = new THREE.Group();

class AudioTexture {
    constructor(file, isWebGL2){
        this.init(file, isWebGL2);
    }
    init(file, isWebGL2){
        const fftSize = 128;
        const listener = new THREE.AudioListener();
        const audio = new THREE.Audio(listener);

        const mediaElement = new Audio(file);
        // mediaElement.play();
        audio.setMediaElementSource(mediaElement);
        
        let analyser = new THREE.AudioAnalyser(audio, fftSize)
        this.analyser = analyser;
        const format = isWebGL2 ? THREE.RedFormat : THREE.LuminanceFormat;
        this.tAudioData = new THREE.DataTexture(
            analyser.data,
            fftSize/2,
            1,
            format
        )
    
    }
    update(){
        if ( this.analyser ) {
            this.analyser.getFrequencyData();
            this.tAudioData.needsUpdate = true;
        }
    }
}
export default class TestModel {
    constructor(){
        this.scene = new Scene();
        this.canvasScene = this.scene.scene;
        // 音频数据可视化
        this.initAudio();
    }

    initAudio(){
        let planeGeometry = new THREE.PlaneGeometry(50, 50);
      
        let vertexShader = `
            varying vec2 vUv;
            void main() {
                vUv = uv;
                gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(position, 1.0);
            }
        `;
        let fragmentShader = `
            uniform sampler2D audioTexture;
            varying vec2 vUv;
            void main() {
                vec3 backgroundColor = vec3(0.125);
                vec3 color = vec3(1.0, 1.0, 0.0);
                float f = texture2D(audioTexture, vec2(vUv.x, 0.0)).r;
                float i = step(vUv.y, f) * step( f - 0.0125, vUv.y );
                gl_FragColor = vec4(mix(backgroundColor, color, i), 1.0);
            }
        `;
        let planeMtl = new THREE.ShaderMaterial({
            vertexShader,
            fragmentShader,
            side:THREE.DoubleSide,
            transparent:true,
            uniforms:{
                audioTexture:{ value:null }
            }
        });
        let planeMesh = new THREE.Mesh(planeGeometry, planeMtl);
        // planeMesh.rotateX(-Math.PI / 2);
        this.canvasScene.add(planeMesh);
        
        document.addEventListener('click', ()=>{
              
            let audioTexture = new AudioTexture('/models/alarm.mp3', false);
            console.log(audioTexture);
       
            planeMtl.uniforms.audioTexture.value = audioTexture.tAudioData;
            planeMesh.onBeforeRender = ()=>{
                audioTexture.update();
            }
        })

        
    
    }
    
}